package cn.itcast.order.service.impl;


import cn.itcast.feign.client.ItemClient;
import cn.itcast.feign.client.UserClient;
import cn.itcast.hmall.dto.common.ResultDTO;
import cn.itcast.hmall.dto.common.ThreadLocalUtil;
import cn.itcast.hmall.dto.order.OrderReqDTO;
import cn.itcast.hmall.pojo.item.Item;
import cn.itcast.hmall.pojo.order.Order;
import cn.itcast.hmall.pojo.order.OrderDetail;
import cn.itcast.hmall.pojo.order.OrderLogistics;
import cn.itcast.hmall.pojo.user.Address;
import cn.itcast.hmall.pojo.user.User;
import cn.itcast.order.constants.OrderConstants;
import cn.itcast.order.mapper.OrderDetailMapper;
import cn.itcast.order.mapper.OrderLogisticsMapper;
import cn.itcast.order.mapper.OrderMapper;
import cn.itcast.order.service.IOrderService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.codec.cli.Digest;
import org.bouncycastle.asn1.dvcs.Data;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 哈纳桑
 * @since 2024-07-13
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {

    @Autowired
    private ItemClient itemClient;
    @Autowired
    private UserClient userClient;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private OrderLogisticsMapper orderLogisticsMapper;

    /**
     * 提交订单
     */
    @Override
    public Long ctreateOrder(OrderReqDTO orderReqDTO) {
        //查询商品信息 调用feign
        Item item = itemClient.getOne(orderReqDTO.getItemId());

        //计算商品价格
        BigDecimal multiply = BigDecimal.valueOf(item.getPrice()).multiply(BigDecimal.valueOf(orderReqDTO.getNum()));
        Long totalFee = Long.valueOf(String.valueOf(multiply));

        //封装Order
        Order order = new Order();
        order.setStatus(OrderConstants.ORDER_STATUS_CREATE);
        order.setTotalFee(totalFee);
        order.setUserId(ThreadLocalUtil.getUserId());
        order.setPaymentType(OrderConstants.PAY_TYPE_BALANCE);

        //order 订单表
        save(order);

        //order-detail 详情表
        OrderDetail orderDetail = new OrderDetail();
        orderDetail.setOrderId(order.getId());
        orderDetail.setItemId(item.getId());
        orderDetail.setNum(orderReqDTO.getNum());
        orderDetail.setName(item.getName());
        orderDetail.setSpec(item.getSpec());
        orderDetail.setPrice(item.getPrice());
        orderDetail.setImage(item.getImage());
        orderDetailMapper.insert(orderDetail);


        //查询地址信息
        Address address = userClient.getAddressID(orderReqDTO.getAddressId());
        OrderLogistics orderLogistics = new OrderLogistics();
        orderLogistics.setOrderId(order.getId());
        orderLogistics.setContact(address.getContact());
        orderLogistics.setCity(address.getCity());
        orderLogistics.setMobile(address.getMobile());
        orderLogistics.setProvince(address.getProvince());
        orderLogistics.setTown(address.getTown());
        orderLogistics.setStreet(address.getStreet());
        orderLogisticsMapper.insert(orderLogistics);

        //扣减库存 feign
        itemClient.stock(orderReqDTO.getItemId(), orderReqDTO.getNum());

        return order.getId();
    }

    @Override
    public ResultDTO payOrder(Long orderId, OrderReqDTO reqDTO) {
        //根据id查询订单信息
        Order order = getById(orderId);

        //查看订单状态
        if (order.getStatus() != OrderConstants.ORDER_STATUS_CREATE) {
            return ResultDTO.error("订单状态错误");
        }

        //验证用户信息
        String passwordMd5 = DigestUtils.md5DigestAsHex(reqDTO.getPassword().getBytes());
        User user = userClient.getUser(ThreadLocalUtil.getUserId());
        if (!passwordMd5.equals(user.getPassword())) {
            return ResultDTO.error("密码错误");
        }

        //扣减余额
       userClient.pay(order.getTotalFee(),user.getId());
        order.setStatus(OrderConstants.ORDER_STATUS_PAY);
        updateById(order);


        return ResultDTO.ok();
    }

    /**
     * 超时订单处理
     */
    @Override
    public void orderTimeOut() {
        // 1.查询出创建状态的订单
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<Order>()
                .eq(Order::getStatus, OrderConstants.ORDER_STATUS_CREATE);

        List<Order> orderList = list(wrapper);

        // 2.筛选出超时的订单 （5分钟内）
        orderList.forEach(order -> {
            LocalDateTime now = LocalDateTime.now();
            Date time = order.getCreateTime();
            // 将java.util.Date转换为LocalDateTime
            LocalDateTime createTime = time.toInstant()
                    .atZone(ZoneId.systemDefault()) // 将Instant转换为特定时区的ZonedDateTime
                    .toLocalDateTime(); // 将ZonedDateTime转换为不带时区的LocalDateTime
            //删除超时订单
            if (now.isAfter(createTime.plusMinutes(5))){
                removeById(order.getId());
                log.warn("超时订单：{} " + order.getId());
            }
        });
    }

}
